<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      v-show="showSearch"
      :inline="true"
      @submit.native.prevent
    >
      <el-form-item label="班组" prop="deptId">
        <el-select
          v-model="queryParams.deptId"
          placeholder="请选择班组"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in deptInfo"
            :key="dict.deptId"
            :label="dict.deptName"
            :value="dict.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="考勤日期" prop="workTime">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="班次" prop="shiftId">
        <el-select
          v-model="queryParams.shiftId"
          placeholder="班次"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in timShiftOptions"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="default"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExportMb"
          >下载通行记录模板
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="default"-->
      <!--          size="mini"-->
      <!--          plain-->
      <!--          @click="handleExport"-->
      <!--          icon="el-icon-download"-->
      <!--          v-hasPermi="['job:attendanceDay:export']"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="default"
          size="mini"
          plain
          @click="handleImport"
          icon="el-icon-upload2"
          v-hasPermi="['job:attendanceDay:import']"
          >导入通行记录
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="default"
          plain
          icon="el-icon-button"
          size="mini"
          @click="handleAttendanceInfo"
          >生成考勤记录
        </el-button>
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getTableRecords"
      ></right-toolbar>
    </el-row>
    <!-- 选中提示 -->
    <div class="choice-tips" v-if="multipleSelection.length > 0">
      <div style="display: flex; align-item: center">
        <i
          class="el-icon-warning"
          style="color: #078fea; font-size: 20px; margin-right: 5px"
        ></i>
        <span style="font-size: 14px"
          >已选择<span style="color: #078fea"
            >&nbsp;{{ multipleSelection.length }}&nbsp;</span
          >项</span
        >
      </div>
    </div>
    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData">
      <el-table-column
        label="序号"
        type="index"
        width="100"
        align="center"
      ></el-table-column>
      <el-table-column
        label="考勤日期"
        prop="workTime"
        min-width="100"
        align="center"
      />
      <el-table-column
        label="班组"
        prop="deptName"
        min-width="80"
        align="center"
      />
      <!--      <el-table-column label="班次" prop="shiftName" min-width="80" align="center"/>-->
      <el-table-column
        label="应出勤人数"
        prop="numberOfAttendance"
        min-width="100"
        align="center"
      />
      <el-table-column
        label="实际出勤人数"
        prop="numberOfActualAttendance"
        min-width="100"
        align="center"
      />
      <el-table-column
        label="异常人数"
        prop="numberOfAbnormal"
        min-width="100"
        align="center"
      />
      <el-table-column
        label="普通迟到人数"
        prop="numberOfLate"
        min-width="100"
        align="center"
      />
      <el-table-column
        label="一般迟到人数"
        prop="numberOfNormallyLate"
        min-width="100"
        align="center"
      />
      <el-table-column
        label="严重迟到人数"
        prop="numberOfSeverelyLate"
        min-width="100"
        align="center"
      />
      <el-table-column
        label="早退人数"
        prop="numberOfLeaveEarly"
        min-width="100"
        align="center"
      />
      <el-table-column
        label="旷工人数"
        prop="numberOfAbsenteeism"
        min-width="100"
        align="center"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['job:attendanceGroup:detail']"
            >明细
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="total > 5"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      :page-sizes="[10]"
      @pagination="getTableRecords"
    />

    <el-dialog
      :title="attendanceInfo.title"
      :visible.sync="attendanceInfo.open"
      width="400px"
      append-to-body
    >
      <div>
        <el-form ref="form" :model="attendanceInfo" label-width="80px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="生成日期" prop="workTime">
                <el-date-picker
                  v-model="attendanceInfo.workTime"
                  value-format="yyyy-MM-dd"
                  type="date"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitAttendanceInfo"
          :loading="loading"
          >{{ loading ? "生成中" : "确 定" }}</el-button
        >
        <el-button @click="attendanceInfo.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {
  listUserDayAttendanceSum,
  userDayAttendanceSumExport,
  attendanceDailyRecord
} from "@/api/job/attendance/attendanceMonth";

import { listRole } from "@/api/job/termSchedule/termSchedule";
import { listTimShift } from "@/api/partTimeJob/workerInfo/workerInfo";
import { tableRecords } from "@/api/system/dept";
export default {
  data() {
    return {
      deptInfo: [],
      attendanceInfo: {
        title: "",
        open: false,
        workTime: undefined
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "工具类导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API + "/workAttendanceApi/saveWorkAttendance"
      },
      tableData: [],
      groupOptions: [],
      dateRange: [],
      loading: false,
      // 导出遮罩层
      exportLoading: false,
      // 表单是否可用
      formEnable: true,
      // 每页数量
      total: 10,
      showSearch: true,
      // 提交表单
      formOpen: false,
      // 表格数据选中列表
      multipleSelection: [],
      // 表格记录
      records: [],
      timShiftOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        shiftId: undefined
      },
      // 表单
      form: {
        title: "新增组织"
      }
    };
  },
  created() {
    this.getTableRecords();
    this.listTimShift();
    this.listDept();
  },
  methods: {
    // 初始化页面
    init() {},
    listDept() {
      tableRecords({ category: 2 }).then(response => {
        this.deptInfo = response.rows;
      });
    },
    /**班次下拉**/
    listTimShift() {
      listTimShift({ status: 1 }).then(response => {
        this.timShiftOptions = response.data;
      });
    },
    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getTableRecords();
    },
    // 表单重置
    reset() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 新增按钮
    handleAdd() {},
    // 删除按钮
    handleDelete() {},
    // 获取表格数据
    getTableRecords() {
      this.loading = true;
      if (this.queryParams.deptId == "") {
        this.queryParams.deptId = undefined;
      }
      listUserDayAttendanceSum(
        this.addDateRange(this.queryParams, this.dateRange)
      ).then(response => {
        this.tableData = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 详情
    handleView(row) {
      let id = row.id;
      let workTime = row.workTime;
      let deptName = row.deptName;
      // console.log("row=",row);
      this.$router.push({
        path: "/attendance/attendanceDayDetail",
        query: { id: id, workTime: workTime, deptName }
      });
    },
    // 修改
    handleUpdate(row) {},
    // 表格多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 重置
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        sourceName: null,
        dateTime: null
      };
      this.getTableRecords();
    },
    // 表单提交
    submit() {},
    // 取消
    cancel() {
      this.formOpen = false;
    },
    // 排序控件
    numChange(v) {
    },
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出每日考勤明细数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.exportLoading = true;
          return userDayAttendanceSumExport(queryParams);
        })
        .then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },

    /** 下载模板操作 */
    handleExportMb() {
      var fileName = "txjl.xlsx";
      window.location.href =
        process.env.VUE_APP_BASE_API +
        "/common/download?fileName=" +
        encodeURI(fileName) +
        "&delete=" +
        false;
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "通行记录信息导入";
      this.upload.open = true;
    },

    /**生成考勤记录**/
    // v1.2修改
    handleAttendanceInfo() {
      this.attendanceInfo.open = true;
      this.attendanceInfo.title = "请选择生成日期";
    },

    /**生成考勤记录提交**/
    submitAttendanceInfo() {
      //请求后台生成考勤记录
      this.loading = true;
      this.exportLoading = true;
      attendanceDailyRecord(this.attendanceInfo.workTime)
        .then(response => {
          this.attendanceInfo.open = false;
          this.msgSuccess("生成成功");
          this.handleQuery();
          this.loading = false;
          this.exportLoading = false;
        })
        .catch(() => {
          this.loading = false;
          this.exportLoading = false;
        });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getTableRecords();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    listRole() {
      listRole().then(response => {
        this.groupOptions = response.rows;
      });
    }
  }
};
</script>

<style scoped>
.choice-tips {
  width: 100%;
  height: 40px;
  background-color: #e6f7ff;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding-left: 10px;
  border-radius: 5px;
  border: 1px solid #bae7ff;
}

.form-inp {
  width: 250px;
}
</style>
